import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router"
import toast from "@/components/toast"

const routes: RouteRecordRaw[] = [
    {
        path: '/',
        redirect: "/home",

    },
    {
        path: '/home',
        component: () => import("@/views/home/home.vue")
    },
    {
        path: '/goods',
        component: () => import("@/views/goods/goods.vue")
    },
    {
        path: '/details/:id',
        component: () => import('@/views/details/details.vue')
    },
    {
        path: '/user',
        component: () => import("@/views/user/user.vue"),
        children: [
            { path: 'center', component: () => import('@/views/user/children/center.vue') },
            { path: 'attack', component: () => import('@/views/user/children/attack.vue') },
            { path: 'cart', component: () => import('@/views/user/children/cart.vue') },
            { path: 'detail', component: () => import('@/views/user/children/detail.vue') },
            { path: 'message', component: () => import('@/views/user/children/message.vue') },
            { path: 'order', component: () => import('@/views/user/children/order.vue') },
            { path: 'address', component: () => import('@/views/user/children/address.vue') },
            { path: 'safe', component: () => import('@/views/user/children/safe.vue') },
        ]
    },
    {
        path: '/order',
        component: () => import("@/views/order/order.vue")
    },
    {
        path: '/free',
        component: () => import("@/views/free/free.vue")
    },
    {

        path: '/:pathMatch(.*)*',
        component: () => import("@/components/error/error.vue")
    }
]

const router = createRouter({
    routes,
    history: createWebHistory()
})

router.beforeEach((to, from, next) => {
    let token = localStorage.getItem('x-auth-token')
    if (to.path.includes('/user') || to.path.includes('/order')) {
        if (token) {
            next()
        } else {
            toast({ str: '请先登录！', type: "warn" })
        }
    } else {
        next()
    }
})


export default router;